import { FC, useRef, useEffect, useState } from "react";
import classNames from "classnames";
import styles from "./index.module.less";

// 定义柱子的位置和尺寸接口
export interface BarPosition {
  x: number; // x坐标的百分比值 (0-100)
  y: number; // y坐标的百分比值 (0-100)
  width: number; // 宽度的百分比值 (0-100)
  height: number; // 高度的百分比值 (0-100)
}

// 定义柱子项接口
export interface BarItem {
  id: string;
  position: BarPosition;
}

interface BarMarkerProps {
  bars: BarItem[]; // 接收柱子数据数组
  viewportSize: { width: number; height: number }; // 视口尺寸
}

// 原始设计尺寸，这是背景图的原始尺寸
const DESIGN_WIDTH = 1920;
const DESIGN_HEIGHT = 1080;

const BarMarker: FC<BarMarkerProps> = ({ bars, viewportSize }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState(1);
  const [offsetX, setOffsetX] = useState(0);
  const [offsetY, setOffsetY] = useState(0);

  // 根据背景图的缩放计算容器的缩放和偏移
  useEffect(() => {
    if (!containerRef.current) return;

    const updateScaleAndOffset = () => {
      const { width: vpWidth, height: vpHeight } = viewportSize;
      
      // 计算背景图的缩放比例 (与background-size: cover逻辑一致)
      const scaleX = vpWidth / DESIGN_WIDTH;
      const scaleY = vpHeight / DESIGN_HEIGHT;
      const newScale = Math.max(scaleX, scaleY);
      
      // 计算居中偏移
      const scaledWidth = DESIGN_WIDTH * newScale;
      const scaledHeight = DESIGN_HEIGHT * newScale;
      const newOffsetX = (vpWidth - scaledWidth) / 2;
      const newOffsetY = (vpHeight - scaledHeight) / 2;
      
      setScale(newScale);
      setOffsetX(newOffsetX);
      setOffsetY(newOffsetY);
    };

    updateScaleAndOffset();
  }, [viewportSize]);

  // 容器样式，模拟background-size: cover的效果
  const containerStyle = {
    transform: `scale(${scale})`,
    transformOrigin: 'top left',
    left: `${offsetX}px`,
    top: `${offsetY}px`,
    width: `${DESIGN_WIDTH}px`,
    height: `${DESIGN_HEIGHT}px`,
  };

  // 计算柱子的位置和尺寸（基于原始设计尺寸）
  const getBarStyle = (bar: BarItem) => {
    const { x, y, width, height } = bar.position;
    
    return {
      left: `${DESIGN_WIDTH * (x / 100)}px`,
      top: `${DESIGN_HEIGHT * (y / 100)}px`,
      width: `${DESIGN_WIDTH * (width / 100)}px`,
      height: `${DESIGN_HEIGHT * (height / 100)}px`,
    };
  };

  // 获取柱子区域的类名
  const getBarClassName = (bar: BarItem) => {
    return classNames(
      styles["bar-marker"],
      {
        // 根据id添加对应的样式类
        [styles[bar.id]]: true
      }
    );
  };

  if (!bars || bars.length === 0) return null;

  return (
    <div className={styles["markers-wrapper"]}>
      <div 
        ref={containerRef} 
        className={styles["markers-container"]} 
        style={containerStyle}
      >
        {bars.map(bar => (
          <div key={bar.id} className={styles["bar-marker-wrapper"]}>
            <div 
              className={getBarClassName(bar)}
              style={getBarStyle(bar)}
            />
          </div>
        ))}
      </div>
    </div>
  );
};

export default BarMarker; 